package com.lizk.thread.sleep;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

import com.lizk.thread.lock.ReentrantLockTest;


/**
 * 测试sleep对中断处理的响应，抛出异常，
 * ①如果是使用synchronized的时候，那么自动释放资源
 * ②如果使用Lock工具，那么不自动释放锁，需要手工在finally中释放
 * @author lizk
 *
 */
public class SleepTest {
	ReentrantLock lock = new ReentrantLock(); 
	Object synLock = new Object();
	
	Runnable r = new Runnable(){
		@Override
		public void run() {
			lock.lock();
			//synchronized (synLock){
			try {
				System.out.println(Thread.currentThread().getName() + "获取锁");
				System.out.println(Thread.currentThread().getName() + "执行开始");
				TimeUnit.SECONDS.sleep(2);
				System.out.println(Thread.currentThread().getName() + "执行结束");
			} catch (InterruptedException e) {
				System.out.println(Thread.currentThread().getName() + "被中断");
				try {
					System.out.println(Thread.currentThread().getName() + "中断等待");
					TimeUnit.SECONDS.sleep(2);
					System.out.println(Thread.currentThread().getName() + "中断结束");
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
				e.printStackTrace();
			}finally {
				//虽然终端使加锁抛出异常，但是如果不解锁，依然不释放资源
				lock.unlock();
				System.out.println(Thread.currentThread().getName() + "释放锁");
			}
			//}
		}
		
	};
	
	public static void main(String[] args) {
		SleepTest test = new SleepTest();
		Thread t1 = new Thread(test.r,"t1");
		Thread t2 = new Thread(test.r,"t1");
		t1.start();
		t2.start();
		try {
			TimeUnit.SECONDS.sleep(1);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		t1.interrupt();
	}
}
